package com.wang.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.wang.demo.dao.PermissionMapper;
import com.wang.demo.dao.UserMapper;
import com.wang.demo.entity.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


/***
 * 该类是来实现UserDetailsService来获取用户信息
 * 得到的信息放到配置类里面进行检验和加密，得到权限后进行分配
 */
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据账户查询用户信息.
        QueryWrapper<com.wang.demo.entity.User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        com.wang.demo.entity.User myUser = userMapper.selectOne(queryWrapper);
        if(myUser!=null){
            //2. 查询改用户具有的权限。
            List<Permission> permissions = permissionMapper.findByUserid(myUser.getUserid());
            //返回UserDetails对象---它是一个接口，返回它的实现类。
            /**
             * String username,账户
             * String password,密码数据库中的密码
             * 	Collection<? extends GrantedAuthority> authorities: 该用户具有的权限
             */
            Collection<? extends GrantedAuthority> authorities=permissions.stream().map(item->new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            System.out.println(authorities);
            User user=new User(username,myUser.getUserpwd(),authorities);
            return user;
        }
        return null;
    }
}
